package com.zzy.base.mvp;

import android.util.Log;

import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

public abstract class BasePresenter<V extends IBaseView,M extends BaseModel> implements IBasePresenter {
    private SoftReference<IBaseView> mReferenceView;

    private V mProxyView;

    private M mModel;


    @Override
    public void attach(IBaseView view) {
        mReferenceView = new SoftReference<>(view);

        mProxyView= (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(mReferenceView==null||mReferenceView.get() ==null){
                    return  null;
                }
                return method.invoke(mReferenceView.get(),args);
            }
        });


        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        if(type!=null){
            try {
                Type[] types=  type.getActualTypeArguments();
                mModel = (M)((Class<?>)types[1]).newInstance();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }

        }

    }

    public V getView() {
        return mProxyView;
    }


    public M getmModel(){
        return mModel;
    }

    @Override
    public void detech() {
        mReferenceView.clear();
        mReferenceView=null;
    }
}
